//
//  LineChart.swift
//  LineChart
//
//  Created by 王枫楠 on 15/11/5.
//  Copyright © 2015年 王枫楠. All rights reserved.
//

import UIKit

protocol LabelViewDelegate {
    func didSelectedIndex(index: NSInteger)
}

@IBDesignable

class LabelView: UIView {
    
    var dayArray = NSArray()
    
    var numOfDays: NSInteger = 0;
    
    private var delegate: LabelViewDelegate?
    private let labelPadind: CGFloat = 45;
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor.clearColor()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
         backgroundColor = UIColor.clearColor()
    }
    
    override func drawRect(rect: CGRect) {
        
        for index in 0..<self.dayArray.count{
            let labelStr = self.dayArray[index]
            
            let frame = CGRectMake(labelPadind * CGFloat(index), 0, 20, 15)
            
            let style = NSMutableParagraphStyle()
            
            style.alignment = NSTextAlignment.Right
            labelStr.drawInRect(frame, withAttributes: [
                NSFontAttributeName : UIFont.boldSystemFontOfSize(12),
                NSForegroundColorAttributeName : UIColor.whiteColor(),
                NSParagraphStyleAttributeName : style])

        }
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        super.touchesBegan(touches, withEvent: event)
        let touch = touches.first!
        let localPoint: CGPoint = touch.locationInView(self)
        let index = NSInteger((localPoint.x+15) / labelPadind)
        print("\(localPoint.x)")
        delegate?.didSelectedIndex(index)
    }
    
}

class LineView: UIView {
    
    private let pointPadding: CGFloat = 45;
    private let lineWidth: CGFloat = 1
    
    var sorceArr: [CGFloat] = Array ()
    var maxValue: CGFloat = 20;
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor.clearColor()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        backgroundColor = UIColor.clearColor()
    }
    
    override func drawRect(rect: CGRect) {
        
        let progressLayer = CAShapeLayer()
        layer.addSublayer(progressLayer)
        UIColor.clearColor().setStroke()
        let lineBackgroundPath = UIBezierPath()
        lineBackgroundPath.moveToPoint(CGPointMake(10, 500))
        lineBackgroundPath.addLineToPoint(CGPointMake(CGFloat(pointPadding*0)+10, ((frame.size.height - (8 * (frame.size.height)) / maxValue))))
        
        for var i = 0; i<self.sorceArr.count ; i++ {
            
                lineBackgroundPath.addLineToPoint(CGPointMake(CGFloat(pointPadding * CGFloat(i))+10, ((frame.size.height - (sorceArr[i] * (frame.size.height)) / maxValue))))
        }
        
        lineBackgroundPath.addLineToPoint(CGPointMake(CGFloat(pointPadding *  CGFloat(sorceArr.count - 1))+10, 500))
        lineBackgroundPath.stroke()
        progressLayer.path = lineBackgroundPath.CGPath
        
        let gradientLayer = CAGradientLayer()
        gradientLayer.startPoint = CGPointMake(0.5, 1.0)
        gradientLayer.endPoint = CGPointMake(0.5, 0.0)
        gradientLayer.frame = CGRectMake(0, 0, bounds.size.width, bounds.size.height)
        gradientLayer.colors = [UIColor(red: 250/255.0, green: 249/255.0, blue: 210/255.0, alpha:0).CGColor,
            UIColor(red: 250/255.0, green: 249/255.0, blue: 210/255.0, alpha: 0.5).CGColor,
            UIColor(red: 250/255.0, green: 249/255.0, blue: 210/255.0, alpha: 1).CGColor]
        self.layer.addSublayer(gradientLayer)
        gradientLayer.mask = progressLayer
        
        UIColor.whiteColor().setStroke()
        let lineBeziPath = UIBezierPath()
        lineBeziPath.lineWidth = 2
        for var i = 0; i<self.sorceArr.count ; i++ {
            if i == 0{
                lineBeziPath.moveToPoint(CGPointMake(pointPadding*CGFloat(i) + 10,((frame.size.height - (sorceArr[i] * (frame.size.height)) / maxValue))))
            }else{
                lineBeziPath.addLineToPoint(CGPointMake(pointPadding*CGFloat(i) + 10, ((frame.size.height - (sorceArr[i] * (frame.size.height)) / maxValue))))
            }
        }
       lineBeziPath.stroke()
    }
    
}

class LineChart: UIView,UIScrollViewDelegate,LabelViewDelegate {
    
    private let screenWidth = UIScreen.mainScreen().bounds.width
    private let scrollLineChartView = UIScrollView()
    private let scrollLabelView = UIScrollView()
    private let lineView = LineView()
    private let labelView = LabelView()
    
    
    
    private var originalScoreAry: [CGFloat] = [8,10,12,15,14,12,16,14,11,10,8,5,2,6,3,6,8,2,3,7,5,8,4,2,4,3,5,5,1,5,3]
    private var dayArray = NSArray()
    private var numOfDays: NSInteger = 30;
    private var target: CGFloat = 5;
    private var maxValue: CGFloat = 20.0;
    private var seleteView = UIView()
    private var selectedDay: NSInteger = 11;
    private var selectedMonth: NSInteger = 11;
    private var dateLabel = UILabel()
    private var selectDayLabel = UILabel()
    private var dateArray = NSArray()
    
    private var selectedHandler: ((index: Int, score: CGFloat) -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor.clearColor()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        backgroundColor = UIColor.clearColor()
    }
    
    override func drawRect(rect: CGRect) {
        
        self.labelView.dayArray = self.dayArray
        
        self.scrollLineChartView.frame =  CGRectMake(screenWidth/7, 0 ,screenWidth-(screenWidth/3.5) ,180)
        
        self.scrollLineChartView.delegate = self
        self.scrollLineChartView.contentSize = CGSizeMake(CGFloat(numOfDays) * 45.0 - 15 ,180)
        
        self.scrollLabelView.frame = CGRectMake(screenWidth/7, CGRectGetMaxY(scrollLineChartView.frame)+10 ,screenWidth-(screenWidth/3.5) ,30)
       
        self.scrollLabelView.delegate = self
        self.scrollLabelView.contentSize = CGSizeMake(CGFloat(numOfDays) * 45.0 - 15 , 30)
        
        self.scrollLabelView.showsHorizontalScrollIndicator = false
        self.scrollLineChartView.showsHorizontalScrollIndicator = false
        
        let paddingView = UIView(frame: CGRectMake(0,CGRectGetMaxY(self.scrollLineChartView.frame),50 * CGFloat(numOfDays) , 1))
        paddingView.backgroundColor = UIColor.lightGrayColor()
        paddingView.alpha = 0.8
        addSubview(paddingView)
        
        let targetVIew = UIView(frame: CGRectMake(0,(scrollLineChartView.frame.height - (scrollLineChartView.frame.height * target)/maxValue ),50 * CGFloat(numOfDays) ,1))
        targetVIew.backgroundColor = UIColor.whiteColor()
        targetVIew.alpha = 0.1
        addSubview(targetVIew)
        
        let targetLabel = UILabel(frame: CGRectMake(5, CGRectGetMinY(targetVIew.frame)-30, 70, 30))
        targetLabel.font = UIFont.systemFontOfSize(11)
        targetLabel.text = "    \(NSInteger(target))W"
        targetLabel.textColor = UIColor.whiteColor()
        addSubview(targetLabel)
        bringSubviewToFront(targetLabel)
        
        labelView.frame = CGRectMake(0, 0, 50 * CGFloat(numOfDays), self.scrollLabelView.frame.height)
        labelView.numOfDays = self.numOfDays
        labelView.delegate = self
        scrollLabelView.addSubview(labelView)

        lineView.frame = CGRectMake(0, 0, 50 * CGFloat(numOfDays), self.scrollLineChartView.frame.height)
        lineView.sorceArr = self.originalScoreAry
        lineView.maxValue = self.maxValue
        scrollLineChartView.addSubview(lineView)
        
        addSubview(self.scrollLineChartView)
        addSubview(self.scrollLabelView)
        
        didSelectedIndex(29)
        
        let dateText = NSMutableAttributedString(string: "\(selectedMonth).\(selectedDay)")
        dateLabel.font = UIFont.systemFontOfSize(30)
        dateLabel.textAlignment = NSTextAlignment.Right
        dateLabel.frame = CGRectMake(screenWidth - 100,0,90,30)
        dateLabel.textColor = UIColor.whiteColor()
        dateLabel.attributedText = dateText
        addSubview(dateLabel)

        self.scrollLineChartView.contentOffset = CGPointMake(CGFloat(numOfDays - 6) * 45.0 + 20, 0);
       
        
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        if scrollView.isEqual(self.scrollLabelView){
            self.scrollLineChartView.contentOffset = scrollView.contentOffset
        }else{
            self.scrollLabelView.contentOffset = scrollView.contentOffset
        }
    }
    
    func didSelectedIndex(index: NSInteger) {
        
        if index < originalScoreAry.count {
     
            let dateString = self.dateArray[index] as! NSString
            let date = dateString.componentsSeparatedByString("-")
//            self.selectedMonth = NSInteger(date[1])!
//            self.selectedDay = NSInteger(date[2])!
            dateLabel.text = "\(date[1]).\(date[2])"
            
            
            self.seleteView.frame = CGRectMake(45*CGFloat(index)+10,((self.scrollLineChartView.frame.size.height - (originalScoreAry[index] * (self.lineView.frame.size.height)) / maxValue)),1,1000)
            self.seleteView.backgroundColor = UIColor.whiteColor()
            self.seleteView.alpha = 0.5
            self.scrollLineChartView.addSubview(seleteView)

            self.selectDayLabel.frame = CGRectMake(self.seleteView.frame.origin.x - 10 ,self.seleteView.frame.origin.y - 20, 40, 10)
            self.selectDayLabel.text = String(format: "%.1fW", originalScoreAry[index])
//            self.selectDayLabel.text = "\(originalScoreAry[index])W"
            self.selectDayLabel.textColor = UIColor.whiteColor()
            self.selectDayLabel.font = UIFont.systemFontOfSize(10)
            self.scrollLineChartView.addSubview(self.selectDayLabel)
            selectedHandler?(index: index+1, score: originalScoreAry[index])
        }
       
        
    }
     // MARK: - Public
    
    func show(dataArray: [NSNumber], dateArray: [NSString], target: CGFloat,maxValue: CGFloat, numOfDays: NSInteger){
        var dataTempArray = [CGFloat]()
        for (var i = dataArray.count-1; i >= 0; i--) {
            let data = dataArray[i]
           dataTempArray .append(CGFloat(data.floatValue))
        }
        self.originalScoreAry = dataTempArray
        
        self.numOfDays = numOfDays
        self.target = target
        self.maxValue = maxValue
        let dayTempArray = NSMutableArray()
        let dateTempArray = NSMutableArray()
        for date in dateArray{
            let dayString = date.substringWithRange(NSMakeRange(8, 2));
            dayTempArray.addObject(dayString)
            dateTempArray.addObject(date)
        }
        
        self.dayArray = dayTempArray.reverseObjectEnumerator().allObjects
        self.dateArray = dateTempArray.reverseObjectEnumerator().allObjects
        let today = NSDate()
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "dd"
        let dayStr: NSString = dateFormatter.stringFromDate(today)
        self.selectedDay = dayStr.integerValue
        dateFormatter.dateFormat = "MM"
        let monthStr: NSString = dateFormatter.stringFromDate(today)
        self.selectedMonth = monthStr.integerValue
  
    }

    
    /**点击回调*/
    func didSelectedHandler(hander: ((index: Int, score: CGFloat) -> Void)?) {
        selectedHandler = hander
    }

}
